package cn.jintongsoft.vras.web;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class WebController {
	private Logger logger = LoggerFactory.getLogger(WebController.class);
	
	@Autowired
	private ApplicationContext applicationContext;
	
	@RequestMapping("/index")
	public Object actionIndex(ModelMap model){
		model.addAttribute("test", "test index page");
		return "/index";
	}
	
	/**
	 * 模拟接口
	 * @param isclient 是否客户端负责合成语音
	 * @param islan 是否允许由用户指定语言
	 * @param lan 携带的语言参数
	 * @param voice 上传的语音文件
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/qa")
	public Object actionQa(boolean isclient, boolean islan, String lan, MultipartFile voice, 
			HttpServletRequest request, HttpServletResponse response){
		try {
			String locale = request.getLocale().toString();
			logger.debug("-------------------");
			logger.debug("isclient=[{}]", isclient);
			logger.debug("islan=[{}]", islan);
			logger.debug("lan=[{}]", lan);
			logger.debug("locale=[{}]", locale);
			logger.debug("ContentType=[{}]", request.getContentType());
			if(voice == null) {
				return null;
			}
			InputStream inputStream = voice.getInputStream();
			String answer = getAnswer(locale, inputStream, islan, lan);
			InputStream down = getVoice(isclient, answer);
			byte[] data = new byte[down.available()];
			down.read(data, 0 ,data.length);
			down.close();
			String result = String.format("data:audio/wav;base64,%s", Base64.encodeBase64String(data));
			//data:audio/wav;base64,
			
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	private String getAnswer(String locale, InputStream inputStream, boolean islan, String lan){
		if(islan){
			//用户指定语言
			if(lan == null || lan.trim().isEmpty()){
				//未携带lan参数
			}else{
				//携带lan参数
			}
		}else{
			//默认获取用户的语言环境
		}
		return "test";
	}
	
	private InputStream getVoice(boolean isclient, String answer) throws IOException{
		String location = "classpath:/static/voice/final.wav";
		Resource resource = applicationContext.getResource(location);
		InputStream src = resource.getInputStream();
		return src;
	}
	
	
	
}
